package com.glqiang.util;

import com.alibaba.fastjson2.JSON;
import com.glqiang.enums.ResultEnum;
import com.glqiang.exception.CustomException;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author glq1218
 */
public class ServletUtils {

    /**
     * 获取String参数
     */
    public static String getParameter(String name) {
        return getRequest().getParameter(name);
    }

    /**
     * 获取Integer参数
     */
    public static Integer getParameterToInt(String name) {
        return Integer.valueOf(getRequest().getParameter(name));
    }

    /**
     * 获取request
     */
    public static HttpServletRequest getRequest() {
        return getRequestAttributes().getRequest();
    }

    /**
     * 获取response
     */
    public static HttpServletResponse getResponse() {
        return getRequestAttributes().getResponse();
    }

    /**
     * 获取session
     */
    public static HttpSession getSession() {
        return getRequest().getSession();
    }

    public static ServletRequestAttributes getRequestAttributes() {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        return (ServletRequestAttributes) attributes;
    }

    /**
     * 将字符串渲染到客户端
     *
     * @param response   渲染对象
     * @param resultEnum 结果枚举
     */
    public static void renderString(HttpServletResponse response, ResultEnum resultEnum) {
        response.setStatus(resultEnum.getCode());
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        try {
            response.getWriter().print(resultEnum.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void renderString(HttpServletResponse response, CustomException customException) {
        response.setStatus(customException.getCode());
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        try {
            response.getWriter().print(customException.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
